// pages/calendar/calendar.js
import Time from "../../utils/time";

var app = getApp();
var api = require('../../utils/interface.js');
import StringTime from "../../utils/time"

let Player = require("../../utils/player"),
    audioList = [],
    player = new Player(),
    playerCurrent = {},
    videoContext = {}
Page({

  /**
   * 页面的初始数据
   */
  data: {
      control: {
          audio: {
              id: "",
              isPlayer: true,
              isPause: false,
              startDate: '00:00',
              progress: "",
              activeProgress: {},
              aniProgress: {},
              initActProgress:{},
              initAniProgress:{},
              loadSucc: false
          },
          player: " ",
          movie: {}
      },
    demo4_days_style: [
      //   month current 当前月 day 日期 color 字体颜色 background 背景颜色
      {
        month: 'current',
        day: 10,
        color: 'white',
        background: '#46c4f3'
      },
      {
        month: 'current',
        day: 22,
        color: 'white',
        background: '#865fc1'
      }
    ],
    //加入日期 已打卡天数 当月打卡天数 当月连续打卡天数
    punchCardDate: {
      addNumber: '2018-06-12',
      punchCardNumber: 30,
      currentMonthNumber: 20,
      currentContinuousMonthNumber: 10,
    },
    monthCard: {},
    userInfo: wx.getStorageSync('userInfo'),
    month: new Date().getFullYear() + "-" + (new Date().getMonth() + 1),
    cgaRef: {},
    pkid: 0,
    isClock: false,
    IsTodayClock:false,

  },
  //点击下一个月,上一个月
  next: function(e) {
    console.log(e);
    this.setData({
      month: e.detail.currentYear + "-" + e.detail.currentMonth
    });
    this.get_calendar_month();
  },
  clockIn: function() {
    var that = this;
    wx.navigateTo({
      url: '../clockIn/clockIn?id=' + that.data.pkid
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setData({
      pkid: options.id,
      IsTodayClock: options.IsTodayClock
    });
    that.initDataTime()
    that.group_calender_total();
    that.get_calendar_month();
    var myDate = new Date();
    var staretime = myDate.getFullYear() + "-" + (myDate.getMonth()+1) + "-" + myDate.getDate();
    
    that.get_detail_list(staretime);
  },
  //获取打卡日历每月信息
  get_calendar_month: function() {
    var that = this;
    var monthList = [];
      let time = new  StringTime()

    app.Post(api.wxapp.group_calender_month, {
      groupId: that.data.pkid,
      yearMonth: that.data.month
    }, function(res) {
      console.log(res.data.MonthDateList1)
        let ahh = res.data.MonthDateList1
      if (res.code == 1) {
        for (var i = 0; i < ahh.length; i++) {
          monthList.push({
            month: 'current',
            day: parseInt(i+1),
            color: '#000',
            background: ahh[i]? '#96c953':'#fff',
              isClockIn:ahh[i]
          });
        }
        console.log(monthList)
        that.setData({
          monthCard: res.data,
          demo4_days_style: monthList
        });
      } else {
        app.WxAlert(res.msg);
      }
    });
  },
  //获取总打卡信息
  group_calender_total: function() {
    var that = this;
    var monthList = [];
    app.Post(api.wxapp.group_calender_total, {
      groupId: that.data.pkid
    }, function(res) {
      if (res.code == 1) {
        that.setData({
          cgaRef: res.data
        });
      } else {
        app.WxAlert(res.msg);
      }
    });
  },
  checkIsClock: function() {
    var that = this;
    app.Post(api.wxapp.check_today_clock, {}, function(res) {
      if (res.code == 1) {
        that.setData({
          isClock: res.data
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
   this. checkIsClock();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
      return {
          title: '测试分享',
          path: 'pages/index/index'
      }
  }
  ,
  datachange:function(e){
    var dataTime = e.detail.year + "-" + e.detail.month+"-"+ e.detail.day,
            mounchList = this.data.demo4_days_style;
    console.log(e)
      this.setData({
          dataTime:dataTime
      })
      for(let i=0;i<mounchList.length;i++){
        if (e.detail.day == mounchList[i].day){
                mounchList[i].background = '#7bcbe8'
        }else {
            if(mounchList[i].isClockIn == true){
                console.log("------------------------ahh")
                mounchList[i].background  ='#96c953'
            }else {
                mounchList[i].background ="#fff"
            }
        }
      }
      this.setData({
          demo4_days_style:mounchList
      })
    console.log(this.data.demo4_days_style)
   this.get_detail_list(dataTime);
  },
   //请求圈子日记列表
  get_detail_list: function (stateTime) {
    
    var that = this;
    app.Post(api.wxapp.clock_detail_list1, {
      groupId: that.data.pkid,
      page: that.data.page,
      size: that.data.size,
      stateTime: stateTime
    }, function (res) {
        that.AudioProgress();
      if (res.code == 1) {
        that.setData({
          detailList:  res.data.ClockDetailList 
        });
        that.initAudio()
      }
    });
  },
    // 初始化录音
    initAudio: function () {
        const that = this,
            detailList = that.data.detailList;
        player.list.clear()
        let audioData = []
        console.log(detailList)
        console.log(player.list)
        audioList = []
        for (let i = 0; i < detailList.length; i++) {
            if (detailList[i].ContentRadio != "") {
                audioList.push({
                    id: "aa",
                    dataUrl: detailList[i].ContentRadio,
                    title: i,
                    index: i,
                })
            }
        }
        console.log(audioList)
        player.list.create(audioList)
        console.log(player.list.info())

    },
    //    录音播放实例
    createAudioPlay: function (e) {
        const that = this,
            control = that.data.control,
            time = new Time(),
            isPlayer = control.audio.isPlayer,
            url = e.currentTarget.dataset.bind
        let index;
        for (let j = 0; j < audioList.length; j++) {
            if (audioList[j].index == url) {
                console.log(audioList[j])
                index = audioList[j]._id
            }
        }
        console.log(":-------------------")
        console.log(player.list.info())
        control.audio.id = url
        console.log(index)
        player.list.syncIndex(audioList[index])
        console.log(player.list.current())

        console.log("别的")
        console.log(player.list.current())
        //      判断是否点击当前录音
        if (player.list.current() != null && playerCurrent.index != url) {
            player.stop()
            //    初始化进度条    点击别的录音
            that.audioProgressAnimation(0, control.audio.progress, "00:00")
            // 全部停止

            console.log("开始播放别的-----------")
            setTimeout(function () {
                player.invoke(index)
            }, 100)
            control.audio.isPlayer = false
            that.setData({
                control: control
            })

            player.event.on('timeupdate', function (data) {
                console.log("开始监听")
                if (data.status == 1) {
                    console.log(data)
                    let startDate = time.secondConvertMinute(data.currentPosition)
                    console.log(startDate)
                    let actWidth = parseFloat(data.currentPosition / data.duration)
                    console.log(actWidth)
                    that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    if ((data.duration - data.currentPosition) == 0) {
                        console.log("audio end")
                        player.stop()
                        control.audio.isPlayer = true
                        that.setData({
                            control: control
                        })
                        that.audioProgressAnimation(0, control.audio.progress, "00:00")
                    } else {
                        //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    }
                }
            })
        }
        else {
            console.log("点击自己")
            player.event.on('timeupdate', function (data) {
                console.log("开始监听")
                if (data.status == 1) {
                    console.log(data)
                    let startDate = time.secondConvertMinute(data.currentPosition)
                    console.log(startDate)
                    let actWidth = parseFloat(data.currentPosition / data.duration)
                    console.log(actWidth)
                    that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    if ((data.duration - data.currentPosition) == 0) {
                        console.log("audio end")
                        player.stop()
                        control.audio.isPlayer = true
                        that.setData({
                            control: control
                        })
                        that.audioProgressAnimation(0, control.audio.progress, "00:00")
                    } else {
                        //that.audioProgressAnimation(actWidth, control.audio.progress, startDate)
                    }
                }
            })

            //点击当当前的录音
            console.log("ahhh")
            // 是否播放
            if (isPlayer) {
                console.log("创建播放")
                if (player.isPaused()) {
                    console.log("继续播放")
                    player.resume()
                }
                else {
                    if (!player.isPlaying()) {
                        console.log("开始播放")
                        player.invoke(index)
                    }
                }
                console.log(player.list.current())
                control.audio.isPlayer = !isPlayer
                that.setData({
                    control: control
                })

            } else {
                if (!player.isPaused()) {
                    player.pause()
                }
                control.audio.isPlayer = !isPlayer
                that.setData({
                    control: control
                })

            }
        }
        playerCurrent = player.list.current()
        console.log(player.list.current())
    },
    //    录音播放进度条
    AudioProgress: function () {
        const that = this,
            control = that.data.control;
        let systemInfo = {}
        wx.getSystemInfo({
            success: res => {
                systemInfo = res
            }
        })
        control.audio.progress = systemInfo.screenWidth * 0.3
        this.setData({
            control: control
        })
    },
    //    录音播放进度条动画
    audioProgressAnimation: function (activeProgress, progresWidth, startDate) {
        const that = this,
            control = that.data.control,
            activePro = wx.createAnimation({}),
            aniPro = wx.createAnimation({}),
            initact = wx.createAnimation({}),
            initani =  wx.createAnimation({})
        //  根据歌曲播放百分比 获取active长度
        const width = progresWidth * activeProgress
        let actWidth = parseFloat(progresWidth - width)
        activePro.width(width * 2).step()
        aniPro.width(actWidth).step()
        initact.width(0).step()
        initani.width(progresWidth).step()

        control.audio.activeProgress = activePro.export()
        control.audio.aniProgress = aniPro.export()
        control.audio.startDate = startDate
        control.audio.initActProgress = initact.export()
        control.audio.initAniProgress = initani.export()
        that.setData({
            control: control
        });
    },
    imgYu: function (event) {
        var src = event.currentTarget.dataset.src; //获取data-src
        var imgList = event.currentTarget.dataset.list; //获取data-list
        //图片预览
        wx.previewImage({
            current: src, // 当前显示图片的http链接
            urls: imgList // 需要预览的图片http链接列表
        })
        this.setData({
            isShuaXing: false
        })

    },
    audioPlay: function () {
        this.setData({
            action: {
                method: 'play'
            }
        });
    },
    videlplay:function(e)
    {
        let index = e.currentTarget.dataset.index
        var log = this.data.detailList;
        log[index].isMviePlayer=true;
        videoContext = wx.createVideoContext('myVideo' + index)
        videoContext.index = index
        videoContext.requestFullScreen({
            duration:0
        })
        console.log("full")
        this.setData({
            detailList:log
        })
    },
    fullVideo:function (e) {
        let log = this.data.detailList
        console.log(e)
        console.log(e.detail.fullScreen)
        if(!e.detail.fullScreen){
            videoContext.pause()
            log[videoContext.index].isMviePlayer=false;
            console.log("结束全屏  ")
            this.setData({
                detailList:log
            })
        }
    },
    ClosedClock:function()
    {

      app.WxAlert("您今天已打卡");
    },
    discuss: function (e) {
      debugger;
      wx.navigateTo({
        url: '../discuss/discuss?id=' + e.currentTarget.dataset.id + "&accid=" + e.currentTarget.dataset.accid
      });
    },
    initDataTime:function () {
      let time = new  StringTime()
        console.log(time.getDateA())
        this.setData({
            dataTime:time.getDateA()
        })
    },
    imgLoad:function (e) {
        console.log(e)
        let screen = wx.getSystemInfoSync()

        var width = e.detail.width,
            height = e.detail.height,
            ratio = width/height
        console.log(ratio)
        var viewWidth = screen.screenWidth*0.8,
            viewHeight = viewWidth / ratio
        let detailList = this.data.detailList
        detailList[e.currentTarget.dataset.bind].img = {
            width:viewWidth,
            height:viewHeight
        }
        this.setData({
            detailList:detailList
        })
    }
})